<template>
  <div id="globalSider">
    <div id="globalSider">
      <a-layout-sider
        v-if="loginUserStore.loginUser.id"
        class="sider"
        width="200"
        breakpoint="lg"
        collapsed-width="0"
      >
        <a-menu
          mode="inline"
          v-model:selectedKeys="current"
          :items="menuItems"
          @click="doMenuClick"
        />
      </a-layout-sider>
    </div>
  </div>
</template>
<script lang="ts" setup>
//存放高亮菜单项
import { computed, h, ref, watch, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { PictureOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/userLoginUserStore.ts'
import { SPACE_TYPE_ENUM } from '@/constants/spaceUser.ts'
import { listMyTeamSpaceUsingPost } from '@/api/spaceUserController.ts'

const loginUserStore = useLoginUserStore()
const router = useRouter()
const current = ref<string[]>([])
//展示我加入的所有团队空间
const teamSpaceList = ref<API.SpaceUserVO[]>([])

//设置高亮 利用路由的前置后置增强，监听路由变化，更新高亮菜单项
router.afterEach((to, from) => {
  current.value = [to.path]
})

const fixItems = [
  {
    key: '/',
    icon: () => h(PictureOutlined),
    label: '公共图库',
  },
  {
    key: '/space/spaceTemp',
    icon: () => h(UserOutlined),
    label: '私有图库',
  },
  {
    key: '/space/addSpace/' + SPACE_TYPE_ENUM.TEAM,
    icon: () => h(TeamOutlined),
    label: '团队空间',
  },
]

const menuItems = computed(() => {
  if (teamSpaceList.value.length < 1) {
    return fixItems
  }
  //展示团队空间分组
  const teamSpaceSubMenus = teamSpaceList.value.map((item) => {
    const space = item.space
    return {
      key: '/space/detail?spaceId=' + space?.id,
      label: space?.spaceName,
    }
  })
  const teamSpaceMenusGroup = {
    type: 'group',
    children: teamSpaceSubMenus,
    label: '我的团队',
    key: 'teamSpace',
  }
  return [...fixItems, teamSpaceMenusGroup]
})

//点击导航栏，路由跳转事件
//这里的key，就是在items中定义好的
const doMenuClick = ({ key }) => {
  router.push(key)
}

const listMyTeamSpace = async () => {
  const resp = await listMyTeamSpaceUsingPost()
  if (resp.data.code === 0 && resp.data.data) {
    teamSpaceList.value = resp.data.data
  }
}

// 替换原来的watchEffect
watchEffect(()=>{
  if (loginUserStore.loginUser.id) {
    listMyTeamSpace()
  }
})
</script>

<style scoped>
#basicLayout .header {
  margin-bottom: 1px;
}

#basicLayout .content {
  padding: 28px;
}

#basicLayout .sider {
  background: #fff;
  padding-top: 20px;
  border-right: 0.5px solid #eee;
}

#basicLayout :deep(.ant-menu-root) {
  border-bottom: none !important;
  border-inline-end: none !important;
}
</style>
